﻿using AutoMapper.QueryableExtensions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NetCore.Dtos;
using NetCore.Entities.Projects;
using NetCore.Extensions;
using NetCore.Interfaces;
using NetCore.Projects.Dtos;
using NetCore.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace NetCore.Projects
{
    /// <summary>
    /// 项目
    /// </summary>
    [Description("项目")]
    public class ProjectAppService : BaseNetCoreAppService<Project>, IProjectAppService
    {
        private readonly IProjectAttachmentAppService _projectAttachmentService;
        private readonly IHttpContextAccessor _httpContext;
        public ProjectAppService(
            IProjectAttachmentAppService projectAttachmentService,
            IHttpContextAccessor httpContext,
            INetCoreRepository<Project> baseRepository) : base(baseRepository)
        {
            _projectAttachmentService = projectAttachmentService;
            _httpContext = httpContext;
        }

        public IQueryable<ProjectDto> GetProjects()
        {
            var result = BaseRepository.GetAll().ProjectTo<ProjectDto>();
            return result;
        }

        public async Task<Project> GetCurrentProject(InputIdDto input)
        {
            //input.Id = AbpSession.UserId;
            var entity = await BaseRepository.GetAsync(input.Id);//默认项目1
            return entity;
        }
        /// <summary>
        /// 获取项目附件
        /// </summary>
        /// <returns></returns>
        public async Task<List<ProjectAttachmentDto>> GetProjectAttachments(InputIdNullDto input)
        {
            var attachments = await _projectAttachmentService.GetProjectAttachments(input);
            attachments.ForEach(m => m.VirtualPath = "/images/projectMap/" + m.ProjectId + "/" + m.FileName);
            return attachments;
        }

        public async Task<ProjectDto> ProjectMap(InputIdDto input)
        {
            var project = await Get(m => m.Id == input.Id).ProjectTo<ProjectDto>().ToListAsync();
            return project.FirstOrDefault();
        }

        public IActionResult Map()
        {
            var path = CustomConfigurationManager.WebRootPath + "/upload/projectMap/";
            var filePath = path + "default.jpg";
            //var fs = new FileStream(filePath, FileMode.Open);
            return FileExtension.PhysicalFile(filePath, "image/jpg", Path.GetFileName(filePath));
        }
        /// <summary>
        ///  没有图片返回一个默认提示错误的图片
        /// </summary>
        /// <returns></returns>
        public IActionResult Error()
        {
            var path = CustomConfigurationManager.WebRootPath + "/upload/projectMap/";
            var filePath = path + "default.jpg";
            //Stream fs = new FileStream(filePath, FileMode.Open);
            return FileExtension.PhysicalFile(filePath, "image/jpg", Path.GetFileName(filePath));
        }



        /// <summary>
        /// IFormFile uploadFile 前端设置的上传文件名(单文件上传)
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult> UploadFile(InputIdDto input)//IFormFile uploadFile 文件过大使用参数获取会出现序列化错误
        {
            try
            {
                //var userId = EngineContext.Current.User.UserId;
                var project = await GetCurrentProject(new InputIdDto{Id = input.Id});
                var order = project.Attachments.Any() ? project.Attachments.Max(m => m.Order ?? 0) : 0;
                string pathForSaving = CustomConfigurationManager.WebRootPath + "/images/projectmap" + project.Id + "/";

                if (FileExtension.CreateFolderIfNeeded(pathForSaving))
                {
                    //foreach (IFormFile uploadFile in Request.Form.Files)
                    {
                        var uploadFile = _httpContext.HttpContext.Request.Form.Files[0];
                        if (uploadFile != null && uploadFile.Length > 0)
                        {
                            var path = Path.Combine(pathForSaving, uploadFile.FileName);
                            //文件名不重复，当已存在同名文件时，还需要先删除文件
                            //ExcelAndFileExtension.ClearFile(path);
                            FileExtension.SavaFile(uploadFile, path);
                            project.Attachments.Add(new ProjectAttachment
                            {
                                FilePath = path,
                                Order = ++order,
                                ProjectId = project.Id,
                                //CreatorId = userId
                            });
                        }
                    }
                }
                return SJson();
            }
            catch (Exception e)
            {
                //throw new Exception(e.Message);
                return EJson(e.Message);
            }
        }

    }
}
